<template>
    <div>
        <el-dialog :title="title" :visible.sync="dialogVisible" width="80%" @close="handleClose">
            <el-form :model="form" :rules="rules" ref="form" label-width="150px" class="demo-ruleForm">
                <el-row>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="标题" prop="headline">
                            <el-input placeholder="请输入标题" v-model="form.headline" maxlength="255"
                                show-word-limit></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="供需类型" prop="supplyType">
                            <el-radio-group v-model="form.supplyType">
                                <el-radio label="0">供给</el-radio>
                                <el-radio label="1">需求</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="联系人" prop="contact">
                            <el-input placeholder="请输入联系人" v-model="form.contact"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="联系方式" prop="contactPerson">
                            <el-input placeholder="请输入联系方式" v-model="form.contactPerson"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="有效期起止" prop="dateVal">
                            <el-date-picker :picker-options="pickerOptions" v-model="form.dateVal" type="datetimerange"
                                value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" @input="changeDate"
                                start-placeholder="开始日期" end-placeholder="结束日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="适用行业" prop="applicableIndustry">
                            <el-select v-model="form.applicableIndustry" placeholder="请选择">
                                <el-option v-for="item in industryData" :key="item.id" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="24" :xl="24">
                        <el-form-item label="关键字" prop="keyword">
                            <el-input placeholder="请输入关键字" v-model="form.keyword" maxlength="255"
                                show-word-limit></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="24" :xl="24">
                        <el-form-item label="描述" prop="description">
                            <el-input placeholder="请输入描述" type="textarea" v-model="form.description" maxlength="2000"
                                show-word-limit></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="24" :xl="24">
                        <el-form-item label="详情" prop="request">
                            <div style="border: 1px solid #ccc;width:98%;line-height:21px;">
                                <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor"
                                    :defaultConfig="toolbarConfig" :mode="mode" />
                                <Editor v-if="dialogVisible" style="height: 400px; overflow-y: hidden;"
                                    v-model="form.request" :defaultConfig="editorConfig" :mode="mode"
                                    @onCreated="onCreated" />
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item label="附件">
                            <el-upload :action="imageUploadUrl" name="file" :on-success="handleAvatarSuccess6"
                                :on-error="handleError6" :on-remove="handleRemove6" :file-list="fileList">
                                <el-button size="small" type="primary" plain>点击上传</el-button>
                                <div slot="tip" class="el-upload__tip">
                                    上传文件大小不超过10M
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <el-form-item class="newIpt" ref="headimgUpload1" label="封面图片" prop="ntThumb">
                            <p class="uploadTip">上传图片不超过10M，且只能上传jpg、png类型</p>
                            <el-upload class="avatar-uploader" :action="imageUploadUrl" :show-file-list="false"
                                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                                :on-error="handleError">
                                <img v-if="imgUrl" :src="imgUrl" class="avatar">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>


                <!-- <el-form-item label="要求" prop="request">
                    <el-input type="textarea" placeholder="请输入要求" v-model="form.request" maxlength="2000" show-word-limit></el-input>
                </el-form-item> -->



                <!-- <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" placeholder="请输入备注" v-model="form.remark" maxlength="500" show-word-limit></el-input>
                </el-form-item> -->



            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="loadingSave" type="primary" @click="submitSave">保存为草稿</el-button>
                <el-button :loading="loading" type="primary" @click="submitForm">提 交</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { eduSupplyAdd, eduSupplyDetail, eduList } from "@/request/api/education"
import { getAddress } from "@/request/api/register"
import rulesUtil from "@/utils/rules"
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getUploadImg, keyVal } from "@/request/api/link"
export default {
    components: { Editor, Toolbar },
    data() {
        return {
            // 设置不能选则当天之前的时间    写data()中
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                },
            },
            loadingSave: false,
            fileAll: [],
            dialogVisible: false,
            fileList: [],
            loading: false,
            imageUploadUrl: '/dev-api/file/upload/uploadNotQR',
            type: "",
            title: "",
            form: {
                id: "", // 传ID 为修改
                allianceId: "", // 产教联合体ID 必填
                supplyType: "", // 供需类型(0 供, 1 需)  必填
                verifyStatus: "", // 审核状态(0 草稿,1 发布,2 下架,3 驳回,4 待审核)  必填 如果是保存 传0 草稿,如果是提交 传4 待审核
                headline: "", // 标题 必填
                keyword: "", // 关键字  必填
                description: "", // 描述  必填
                request: "", // 要求  必填
                contactPerson: "", // 联系方式
                contact: "", // 联系人
                startTime: "", // 开始时间
                endTime: "", // 结束时间
                province: "", // 所在地省  必填
                city: "", // 所在地 市  必填
                area: "", // 所在地 区县  必填
                address: "", // 详细地址  必填
                remark: "",
                fileDtos: [ //附件 可多个
                    // {
                    //     name: "", // 附件名称
                    //     filePath: "" // 附件路径
                    // }
                ],
                zoneName: []
            },
            rules: {
                headline: [
                    { required: true, message: '请输入标题', trigger: 'blur' },
                ],
                contact: [
                    { required: true, message: '请输入联系人', trigger: 'blur' },
                ],
                contactPerson: [
                    { required: true, validator: rulesUtil.FormValidate.Form().checkTel, trigger: 'blur' },
                ],
                keyword: [
                    { required: true, message: '请输入关键字', trigger: 'blur' },
                ],
                description: [
                    { required: true, message: '请输入描述', trigger: 'blur' },
                ],
                request: [
                    { required: true, message: '请输入详情', trigger: 'blur' },
                ],
                supplyType: [
                    { required: true, message: '请选择类型', trigger: 'change' },
                ],
                dateVal: [
                    { required: true, message: '请选择时间', trigger: 'blur' },
                ],
                applicableIndustry: [
                    { required: true, message: '请选择适用行业', trigger: 'change' },
                ],
                // zoneName: [
                //     { required: true, message: '请选择', trigger: 'change' },
                // ],
            },
            dataTree: [],
            disabled: false,
            dialogVisibleSmall: false,
            dialogImageUrl: '',
            imgUrl: '',
            zoneData: [],
            selectCate2: {
                // checkStrictly: true,
                label: "name",
                children: "children",
                value: "name",
                emitPath: true,
                getCheckedNodes: true,
                expandTrigger: "hover",
            },
            editor: null,
            toolbarConfig: {//工具栏配置
                excludeKeys: [
                    'insertTable',//插入表格
                ]
            },
            editorConfig: {
                placeholder: '请输入内容...',
                // 所有的菜单配置，都要在 MENU_CONF 属性下
                MENU_CONF: {
                    //配置上传图片
                    uploadImage: {
                        customUpload: this.uploadImg,
                    },
                    //配置上传视频
                    uploadVideo: {
                        customUpload: this.uploadVideo
                    }
                },
            },
            mode: 'default', // or 'simple'
            registrationType: '',//
            industryData: []
        };
    },

    methods: {
        open(type, info) {
            this.getIndustryType()
            // 获取当前用户类型
            var userInfo = JSON.parse(window.sessionStorage.getItem("userInfo"));
            this.registrationType = userInfo.registrationType
            // if (this.registrationType == '6') {//教培组织
            //     this.form.supplyType = '0'
            // } else {//政府、企业、民非组织
            //     this.form.supplyType = '1'
            // }
            this.type = type;
            this.dialogVisible = true;
            this.getZoning()
            this.getEdu()//获取联合体列表
            this.fileList = []
            if (this.type === "add") {
                this.title = "新增";
                this.fileList = []
            } else if (this.type === "edit") {
                this.title = "编辑";
                this.form.id = info.id
                this.getDetail(info.id)
            }
        },
        // 获取区划
        getZoning() {
            getAddress().then(res => {
                if (res.data.code === 200) {
                    this.zoneData = res.data.result
                }
            })
        },
        // 获取联合体列表
        getEdu() {
            eduList().then(res => {
                if (res.data.code == 200) {
                    let dataList = res.data.result.items
                    dataList.forEach(item => {
                        if (item.allianceType == '1') {
                            this.form.allianceId = item.id
                        }
                    })
                }
            })
        },
        // 区划
        selectValue2(val) {
            this.$refs.cascader2.dropDownVisible = false;
        },
        // 获取适用行业
        getIndustryType() {
            keyVal('applicable_industry ').then(res => {
                console.log(res, '1111')
                if (res.data.code === 200) {
                    this.industryData = res.data.result.items

                }
            })
        },
        changeDate(val) {
            console.log(val)
            this.form.startTime = val[0]
            this.form.endTime = val[1]
            this.$forceUpdate()//强制刷新
        },
        handleClose() {
            this.$emit('getResoure')
            this.$refs.form.resetFields();
        },
        // 获取详情
        getDetail(id) {
            eduSupplyDetail(id).then(res => {
                if (res.data.code === 200) {
                    this.imgUrl = res.data.result.thumb
                    this.form = res.data.result
                    this.form.dateVal = [res.data.result.startTime, res.data.result.endTime]
                    this.form.zoneName = [res.data.result.province, res.data.result.city, res.data.result.area]
                    var imgs = res.data.result.fileDtos;
                    this.form.fileDtos = res.data.result.fileDtos;
                    imgs.forEach((item) => {
                        this.fileList.push({
                            filePath: item.filePath,
                            id: item.id,
                            name: item.name
                        });
                    });
                }
            })
        },
        // 新增接口
        addResult(params) {
            eduSupplyAdd(params).then((res) => {
                this.loading = false
                this.loadingSave = false
                if (res.data.code === 200) {
                    this.$message({
                        message: res.data.message,
                        type: "success",
                    });
                    this.dialogVisible = false
                    this.$router.push("/federationList");
                } else {
                    this.$message.error(res.data.message);
                }
            });
        },
        // 修改接口
        editResult(params) {
            eduSupplyAdd(params).then((res) => {
                this.loading = false
                this.loadingSave = false
                if (res.data.code === 200) {
                    this.$message({
                        message: res.data.message,
                        type: "success",
                    });
                    this.dialogVisible = false


                } else {
                    this.$message.error(res.data.message);
                }
            });
        },
        // 创建-保存
        submitSave() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.loadingSave = true
                    if (this.type === 'add') {
                        let params = { ...this.form }
                        if (params.zoneName.length !== 0) {
                            params.province = params.zoneName[0]
                            params.city = params.zoneName[1]
                            params.area = params.zoneName[2]
                        }
                        delete params.dateVal
                        delete params.zoneName
                        params.verifyStatus = '0'
                        console.log(params)
                        this.addResult(params)
                    } else if (this.type === 'edit') {
                        let params = { ...this.form }
                        if (params.zoneName.length !== 0) {
                            params.province = params.zoneName[0]
                            params.city = params.zoneName[1]
                            params.area = params.zoneName[2]
                        }
                        var imgList = params.fileDtos;
                        var newImg = [];
                        imgList.forEach((item) => {
                            newImg.push({
                                filePath: item.filePath,
                                name: item.name,
                            });
                        });
                        params.fileDtos = newImg;
                        delete params.dateVal
                        delete params.zoneName
                        params.verifyStatus = '0'
                        console.log(params)
                        this.editResult(params)
                    }

                } else {
                    return false;
                }
            });
        },
        // 创建-提交
        submitForm() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.loading = true
                    if (this.type === 'add') {
                        let params = { ...this.form }
                        if (params.zoneName.length !== 0) {
                            params.province = params.zoneName[0]
                            params.city = params.zoneName[1]
                            params.area = params.zoneName[2]
                        }
                        delete params.dateVal
                        delete params.zoneName
                        params.verifyStatus = '4'
                        console.log(params)
                        this.addResult(params)
                    } else if (this.type === 'edit') {
                        let params = { ...this.form }
                        if (params.zoneName.length !== 0) {
                            params.province = params.zoneName[0]
                            params.city = params.zoneName[1]
                            params.area = params.zoneName[2]
                        }
                        delete params.dateVal
                        delete params.zoneName
                        var imgList = params.fileDtos;
                        var newImg = [];
                        imgList.forEach((item) => {
                            newImg.push({
                                filePath: item.filePath,
                                name: item.name,
                            });
                        });
                        params.fileDtos = newImg;
                        params.verifyStatus = '4'
                        console.log(params)
                        this.editResult(params)
                    }

                } else {
                    return false;
                }
            });
        },
        // 上传文件成功
        handleAvatarSuccess(response, file) {
            this.imgUrl = URL.createObjectURL(file.raw);
            this.form.thumb = response.message;
            this.$refs.headimgUpload1.clearValidate(); // 关闭校验
        },
        // 上传文件失败
        handleError(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因:${errInfo.message}`);
        },
        // 限制上传的类型
        beforeAvatarUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (!isLt10M) {
                this.$message.error("上传图片大小不能超过 10M!");
                return false;
            }
            var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
            const extension = testmsg === "jpg" || testmsg === "JPG";
            const extension2 = testmsg === "png" || testmsg === "PNG";
            if (!extension && !extension2) {
                this.$message({
                    message: "上传图片只能是 jpg, png格式!",
                    type: "error",
                });
                return false;
            }
        },
        // 富文本
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
        // 富文本-上传图片
        uploadImg(file, insertFn) {
            let imgData = new FormData();
            imgData.append('file', file);
            //调接口，上传图片
            getUploadImg(imgData).then(response => {
                if (response.data.code == 200) {
                    insertFn(response.data.message);
                } else {
                    this.$message.error(response.data.message);
                }
            })
        },
        // 富文本-上传视频
        uploadVideo(file, insertFn) {
            let imgData = new FormData();
            imgData.append('file', file);
            //调接口，上传图片
            getUploadImg(imgData).then(response => {
                if (response.data.code == 200) {
                    insertFn(response.data.message);
                } else {
                    this.$message.error(response.data.message);
                }
            })
        },
        // 上传文件成功
        handleAvatarSuccess6(response, file) {
            let params = {
                name: file.name,
                filePath: file.response.message,
            }
            this.form.fileDtos.push(params);
        },
        // 上传文件失败
        handleError6(err) {
            let errInfo = JSON.parse(err["message"]);
            this.$message.error(`文件上传失败，原因：${errInfo.message}`);
        },
        // 文件上传删除
        handleRemove6(response) {
            var dataList = this.form.fileDtos;
            if (response.id) {
                for (var i = 0; i < dataList.length; i++) {
                    if (dataList[i].id.indexOf(response.id) > -1) {
                        var index = i;
                        dataList.splice(index, 1); //存在即删除
                    }
                }
            } else {
                for (var j = 0; j < dataList.length; j++) {
                    if (dataList[j].name.indexOf(response.name) > -1) {
                        var index2 = j;
                        dataList.splice(index2, 1); //存在即删除
                    }
                }
            }
            this.form.fileDtos = dataList;
        },
    },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="less" scoped>
/*.el-input {
    width: 450px;
}



.el-textarea {
    width: 450px;
}
*/
.el-cascader {
    width: 100%;
}

/deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}</style>

